package main

import (
	"fmt"
	"html/template"
	"io/ioutil"
	"net/http"
	"path/filepath"
	"poker21/model"
	"poker21/service"
	"poker21/utils"
	"time"
)

func main() {
	rootPath, err := filepath.Abs("")
	fmt.Printf("rootPath: %v, err: %v \n", rootPath, err)

	// playGame21() //玩游戏21点

	fmt.Println("\n-------sdfdsf----开始21---")
	str := utils.ToString(65)
	fmt.Printf("str: %v \n", str)

	//----------http-get/post-begin
	// http.HandleFunc("/", HttpPostServer)
	// http.ListenAndServe(":9091", nil)
	//----------http-get/post-end

	//----------http-begin
	// toHttp()
	//----------http-end

	cardsHtml() //把扑克牌显示在浏览器上html

}

// html ++++++++++ begin
func cardsHtml() {
	http.HandleFunc("/", showCards)
	http.Handle("/web/", http.StripPrefix("/web/", http.FileServer(http.Dir("web"))))
	err := http.ListenAndServe(":8090", nil)
	if err != nil {
		fmt.Printf("err: %v \n", err)
	}
}
func showCards(w http.ResponseWriter, r *http.Request) {
	//解析指定文件生成模板对象
	tmlp, err := template.ParseFiles("./web/cards.html")
	if err != nil {
		fmt.Printf("生成模板错误err: %v \n", err)
		return
	}

	cardNumArr := [2]int{54, 2}                //参数1:一副牌54张,参数2:生成多少副牌
	var d model.Deck                           //实例化牌
	d.Initialize(cardNumArr[0], cardNumArr[1]) //创建牌
	shuffleTimes := 2                          //洗牌次数
	for ii := 0; ii < shuffleTimes; ii++ {
		d.Shuffle() //洗牌几次
	}
	// fmt.Printf("-d-: %+v \n", d)
	d.CardsNameConcat() //拼接

	tmlp.Execute(w, d)
}

// html ++++++++++ end

func toHttp() {
	http.HandleFunc("/", func(w http.ResponseWriter, r *http.Request) {
		fmt.Fprintf(w, "hello world")
	})
	http.HandleFunc("/time", func(w http.ResponseWriter, r *http.Request) {
		t := time.Now()
		timeStr := fmt.Sprintf("{\"time\": \"%s\"}", t)
		w.Write([]byte(timeStr))
	})
	http.ListenAndServe(":8080", nil)
}

// server获取http发的数据处理[get,post,push...]
func HttpPostServer(w http.ResponseWriter, r *http.Request) {
	defer r.Body.Close() //关闭
	//r.ParseForm()        //解析contentType := "application/x-www-form-urlencoded" //表单提交数据
	// fmt.Printf("ParseForm:%#v, name:%v, age:%v\n", r.ParseForm(), r.ParseForm().Get("name"), r.ParseForm().Get("age"))

	b, err := ioutil.ReadAll(r.Body) //contentType := "application/json" //解析json提交
	if err != nil {
		fmt.Printf("获取数据失败：%v\n", err)
		return
	}
	fmt.Printf("server获取数据：%v", string(b))
	answer := `{"status":"ok"}`
	w.Write([]byte(answer))
}

// 21点游戏
func playGame21() {
	service.OnGameInit()
}
